<template>
  <div style="display: flex;">
    <!--  视频  -->
    <div style="width:400px;height:400px">
      <input type="file" id="file" accept=".mp4" @change="changeFile($event)"/>
      <br/>
      <video  style="width: 400px;" id="player" autoplay controls src=""
              @play="playVideo($event)"
              @render="renderVideo($event)">
      </video>
      <canvas id="canvas"></canvas>
    </div>
    <!--  字符画像  -->
    <div style="margin-left:20px;width: 560px;height: 600px;background-color: #ffffff">
      <div id="char" class="char"></div>
    </div>

  </div>
</template>

<script>

export default {
  name: "CharacterPage",
  data(){
    return{

    }
  },
  methods:{
    //监听文件变化
    changeFile(e){
      console.log("e-----",e.target.files)
      let file = e.target.files[0];
      let fileReader = new FileReader();
      fileReader.addEventListener("load",(e)=>{
        console.log("fileReader===",fileReader,e)
        document.getElementById("player").setAttribute('src',fileReader.result);
      });
      fileReader.readAsDataURL(file);
    },
    //监听视频播放
    playVideo(e){
      let render = function (){
          let event = new CustomEvent("render");
          document.getElementById("player").dispatchEvent(event);
          if (!document.getElementById("player").ended && !document.getElementById("player").paused){
            requestAnimationFrame(render)
          }
      }
      requestAnimationFrame(render)
    },
    //监听视频播放速率，创建画板
    renderVideo(e){
      let ctx = document.getElementById("canvas").getContext("2d");
      ctx.drawImage(document.getElementById("player"),0,0,140,80);
      let data = ctx.getImageData(0,0,140,80);
      let html =  this.pixelsTransForm(data);

      document.getElementById("char").innerHTML = html;

      console.log("html------",html)
    },
    //像素点转字符
    pixelsTransForm(imageData){
      let pixelsData = imageData.data;
      let width = imageData.width;
      let height = imageData.height;
      let charData = [];

      for (let row = 0; row < height; row++){
        let rowData = [];
        for (let col = 0; col < width; col++) {
          let r = pixelsData[(width*row+col) * 4 + 0];
          let g = pixelsData[(width*row+col) * 1 + 1];
          let b = pixelsData[(width*row+col) * 4 + 2];
          let grey = r*0.299 + b*0.587 + g*0.114;
          rowData.push(grey);
        }
        charData.push(rowData);
      }

      console.log("charData----",charData)

      let map = ['$','6','3','7','!',':','.','&nbsp'];

      return charData.map(row=>{
        return row.map(grey=>map[parseInt(grey/255*map.length)]).join('')+'<br/>';
      }).join('');

    }
  }
}
</script>

<style scoped>
  .char{
    margin-top: -30px;
    margin-left: -80px;
    font-family: Courier;
    font-size: 12px;
    transform: scale(0.5);
    width: 400px;
    height: 200px
  }
</style>
